import globalMethods from '@/utils/global-methods'

export default {
  namespaced: true,
  state: {
    pathMap: [],
    activeKey: null,
    cachePages: []
  },
  getters: {
    GET_PATHMAP(state) {
      const pathMapCache = sessionStorage.getItem('tabPathMap') ? JSON.parse(sessionStorage.getItem('tabPathMap')) : null
      return state.pathMap || pathMapCache
    },
    GET_PATH_MAP(state) {
      let cacheTabs = globalMethods.$storageGet('tabs', [])
      return state.pathMap || cacheTabs
    },
    CACHE_PAGES(state) {
      return state.cachePages || []
    }
  },
  mutations: {
    SET_PATHMAP(state, map) {
      state.pathMap = map
    },
    SET_ACTIVE_KEY(state, activeKey) {
      state.activeKey = activeKey
    },
    CLEAR_PATHMAP(state) {
      state.pathMap = []
      globalMethods.$storageClear('tabs')
    },
    ADD_CACHE_PAGE(state, page) {
      // console.log('ADD_CACHE_PAGE', page)
      if (page && page !== 'RouteView') {
        let res = state.cachePages.find(v => v === page)
        if (!res) {
          state.cachePages.push(page)
        }
      }
    },
    DEL_CACHE_PAGE(state, page) {
      // console.log('DEL_CACHE_PAGE', page)
      if (page && page !== 'RouteView') {
        // console.log('删除' + page)
        let resIndex = state.cachePages.findIndex(v => v === page)
        if (resIndex !== -1) {
          // console.log('删除' + page + '成功')
          state.cachePages.splice(resIndex, 1)
        }
      }
    },
    DEL_CACHE_PAGES(state, pages) {
      // console.log('DEL_CACHE_PAGES', pages)
      pages.history && pages.history.map(v => {
        if (v.componentName && v.componentName !== 'RouteView') {
          // console.log('pages删除' + v.componentName)
          let resIndex = state.cachePages.findIndex(w => w === v.componentName)
          // console.log(resIndex)
          if (resIndex !== -1) {
            state.cachePages.splice(resIndex, 1)
          }
        }
      })
    },
    CLEAN_CACHE_PAGE(state) {
      state.cachePages = []
    }
  }
}